package com.zkzx.util.ftp.utils;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.zkzx.util.ftp.FtpClient;
import com.zkzx.util.ftp.FtpClientConfig;
import com.zkzx.util.ftp.FtpClientFactory;
import com.zkzx.util.ftp.FtpFile;
import com.zkzx.util.ftp.enums.FtpClientTypeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author youwei
 * @date 2019年12月5日
 **/
@Component
public class FtpUtil {

    private FtpClient ftpClient;

    @NacosValue(value = "${ftpIp:182.92.75.88}", autoRefreshed = true)
    private String ftpIp;

    @NacosValue(value = "${ftpPort:22}", autoRefreshed = true)
    private Integer ftpPort;

    @NacosValue(value = "${ftpUserName:mysftp}", autoRefreshed = true)
    private String ftpUserName;

    @NacosValue(value = "${ftpPassword:mysftp}", autoRefreshed = true)
    private String ftpPassword;

    @NacosValue(value = "${ftpReadFilePath:/upload}", autoRefreshed = true)
    private String ftpReadFilePath;

    @NacosValue(value = "${ftpType:SFTP}", autoRefreshed = true)
    private String ftpType;

    @NacosValue(value = "${fileEncoding:UTF-8}", autoRefreshed = true)
    private String fileEncoding;

    public FtpClient getFtpClient() {
        if (null == ftpClient) {
            FtpClientConfig ftpClientConfig = FtpClientConfig.getDefaultConfig();
            ftpClientConfig.setControlEncoding(fileEncoding);
            ftpClient = FtpClientFactory.getFtpClient(FtpClientTypeEnum.valueOf(ftpType), ftpClientConfig);
        }

        ftpClient.connect(ftpIp, ftpPort, ftpUserName, ftpPassword);
        ftpClient.enterLocalPassiveMode();
        ftpClient.binary();
        return ftpClient;
    }

    public List<String> getLikeFileNameList(String filePath, String likeName, FtpClient ftpClient) {
        List<FtpFile> ftpFileList = ftpClient.ls(filePath);
        if (CollectionUtils.isEmpty(ftpFileList)) {
            throw new RuntimeException("没有找到文件");
        }

        List<String> nameList = ftpFileList.stream()
                .filter(ftpFile -> ftpFile.getName().contains(likeName)
                        || likeName.contains(ftpFile.getName()))
                .map(FtpFile::getName)
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(ftpFileList)) {
            throw new RuntimeException("没有找到文件");
        }
        return nameList;
    }

}
